<template>
  <div class="usersBox">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model.lazy="queryInfo.query"
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
            @keyup.enter.native="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="stateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="slot">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="openEdit(slot.row)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteHandle(slot.row.id)"
            />
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="success"
                icon="el-icon-s-tools"
                size="small"
                @click="showRoleDialog(slot.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="dialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRule"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="editVisible"
      width="50%"
      :before-close="handleClose"
      @close="eidtClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRule"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="roleVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>分配新角色：<el-select v-model="roleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkEmail = (rule, value, cb) => {
      let emailRule = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
      if (emailRule.test(value)) {
        return cb();
      } else {
        return cb(new Error("请输入正确格式的邮箱"));
      }
    };
    const checkMobile = (rule, value, cb) => {
      let mobileRule = /^1[3|4|5|7|8][0-9]{9}$/;
      if (mobileRule.test(value)) {
        return cb();
      } else {
        return cb(new Error("请输入正确格式的手机号"));
      }
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      userList: [],
      dialogVisible: false,
      editVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {
        id: "",
        username: "",
        email: "",
        mobile: "",
      },
      addFormRule: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      editFormRule: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      userInfo: {},
      roleVisible: false,//分配角色对话框是否展示
      roleList:[],
      roleId:undefined,
    };
  },
  created() {
    this.getUserList();
    this.getRoleList()
  },
  methods: {
    openEdit(rowData) {
      this.editForm = rowData;
      this.editVisible = true;
    },
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    async stateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新状态失败");
      } else {
        return this.$message.success("更新状态成功");
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    dialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    eidtClose() {
      this.$refs.editFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post("users", this.addForm);
          if (res.meta.status === 201) {
            this.$message.success("添加用户成功");
            this.dialogVisible = false;
            this.getUserList();
          } else {
            this.$message.error("添加用户失败");
          }
        }
      });
    },
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            this.editForm
          );
          if (res.meta.status === 200) {
            this.$message.success("更新用户成功");
            this.editVisible = false;
            this.getUserList();
          } else {
            this.$message.error("更新用户失败");
          }
        }
      });
    },
    async deleteHandle(id) {
      await this.$confirm("此操作将永久删除该文件, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status !== 200) {
            this.$message.error("删除用户失败");
          } else {
            this.$message.success("删除用户成功");
            this.getUserList();
          }
        })
        .catch(() => this.$message.info("已取消删除"));
    },
    //获取当前行用户信息，并展示分配角色对话框
    showRoleDialog(userInfo) {
      this.userInfo = userInfo;
      this.roleVisible = true;
    },
    //获取角色列表信息
    async getRoleList(){
      const {data:res} = await this.$http.get('roles');
      if(res.meta.status !== 200){
        return this.$message.error('获取用户角色失败')
      }
      this.roleList = res.data;
    },
    //分配角色
    async allotRole(){
     
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.roleId
      });
      if(res.meta.status !== 200){
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功');
      this.roleVisible = false;
      this.userInfo = {};
      this.roleId = undefined;
      this.getUserList()
    }
  },
};
</script>

<style lang="less" scoped>
.usersBox {
  .el-table {
    margin-top: 20px;
  }
  .el-select{
    margin-top: 20px;
  }
}
</style>